package io.renren.modules.medical.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.MedicalException;
import io.renren.common.result.ResultCodeEnum;
import io.renren.common.utils.DoctorInfoUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.medical.dao.IllSubDao;
import io.renren.modules.medical.entity.BaseEntity;
import io.renren.modules.medical.entity.DoctorInfoEntity;
import io.renren.modules.medical.entity.IllSubEntity;
import io.renren.modules.medical.entity.PatientDoctorRelativeEntity;
import io.renren.modules.medical.service.DoctorInfoService;
import io.renren.modules.medical.service.IllSubService;
import io.renren.modules.medical.vo.medicalVo.IllSubAndChildrenVo;
import io.renren.modules.medical.vo.medicalVo.IllSubTitleAndIdVo;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.jdom2.Parent;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 系统管理员才拥有权限增删改查功能
 */
@RequiredArgsConstructor
@Service("illSubService")
public class IllSubServiceImpl extends ServiceImpl<IllSubDao, IllSubEntity> implements IllSubService {

    private final DoctorInfoService doctorInfoService;

    private final SysUserService sysUserService;

    /**
     * 获取到病情分类树
     */
    @Override
    public List<IllSubAndChildrenVo> listWithTree() {
        List<IllSubEntity> oneLevelList = getChildren(0L);
        DoctorInfoEntity doctorInfo = DoctorInfoUtils.getDoctorInfo(doctorInfoService);
        Long depId = doctorInfo.getDepId();
        oneLevelList = oneLevelList.stream().filter(item -> !item.getId().equals(depId)).collect(Collectors.toList());

        // 将集合封装进IllSubAndChildrenVo
        List<IllSubAndChildrenVo> illSubAndChildrenVos = oneLevelList.stream().map(item -> {
            IllSubAndChildrenVo oneLevelVo = new IllSubAndChildrenVo();
            BeanUtils.copyProperties(item, oneLevelVo);
            // 封装集合的子集
            List<IllSubEntity> twoLevelList = getChildren(item.getId());
            List<IllSubAndChildrenVo> childrenVos = twoLevelList.stream().map(twoLevel -> {
                IllSubAndChildrenVo twoLevelVo = new IllSubAndChildrenVo();
                BeanUtils.copyProperties(twoLevel, twoLevelVo);
                return twoLevelVo;
            }).collect(Collectors.toList());
            oneLevelVo.setChildren(childrenVos);
            return oneLevelVo;
        }).collect(Collectors.toList());

        return illSubAndChildrenVos;
    }

    /**
     * 根据父id获取子分类的集合
     */
    @Override
    public List<IllSubEntity> getChildren(Long parentId) {
        LambdaQueryWrapper<IllSubEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(IllSubEntity::getParentId, parentId);
        queryWrapper.orderByAsc(IllSubEntity::getSort);
        return this.list(queryWrapper);
    }

    @Override
    public void updateIllsub(IllSubEntity illSub) {
        // 判断名称是否重复
        LambdaQueryWrapper<IllSubEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(IllSubEntity::getTitle, illSub.getTitle());
        queryWrapper.eq(IllSubEntity::getParentId, illSub.getParentId());
        IllSubEntity subEntity = this.getOne(queryWrapper);
        if (subEntity != null && !subEntity.getId().equals(illSub.getId())) {
            throw new MedicalException(ResultCodeEnum.NAME_REPETITION_ERROR.getCode(), "分类名称已存在");
        }

        this.updateById(illSub);
    }

    @Override
    public void saveIllsub(IllSubEntity illSub) {
        // 判断名称是否重复
        LambdaQueryWrapper<IllSubEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(IllSubEntity::getTitle, illSub.getTitle());
        queryWrapper.eq(IllSubEntity::getParentId, illSub.getParentId());
        if (this.count(queryWrapper) > 0) {
            throw new MedicalException(ResultCodeEnum.NAME_REPETITION_ERROR.getCode(), "分类名称已存在");
        }

        this.save(illSub);
    }

    @Override
    public List<IllSubTitleAndIdVo> getOneLevelList() {
        List<IllSubEntity> onLevelList = getChildren(0L);
        List<IllSubTitleAndIdVo> illSubTitleAndIdVo = onLevelList.stream().map(item -> {
            IllSubTitleAndIdVo illSubAndChildrenVo = new IllSubTitleAndIdVo();
            BeanUtils.copyProperties(item, illSubAndChildrenVo);
            return illSubAndChildrenVo;
        }).collect(Collectors.toList());
        return illSubTitleAndIdVo;
    }

    @Override
    public List<IllSubTitleAndIdVo> getBasicTwoList() {
        // 直接获取到当前医生的病情分类
        DoctorInfoEntity doctorInfo = DoctorInfoUtils.getDoctorInfo(doctorInfoService);
        Long depId = doctorInfo.getDepId();
        // 先判断当前的depId是不是膝关节炎的depId
        boolean isGonitis = DoctorInfoUtils.isGonitis(depId, this);
        List<IllSubTitleAndIdVo> illSubTitleAndIdVos = new ArrayList<>();
        // 如果是的话就直接返回一个父级病情
        if (isGonitis) {
            IllSubEntity illSubEntity = this.getById(depId);
            IllSubTitleAndIdVo illSubTitleAndIdVo = new IllSubTitleAndIdVo();
            BeanUtils.copyProperties(illSubEntity, illSubTitleAndIdVo);
            illSubTitleAndIdVos.add(illSubTitleAndIdVo);
        } else {
            // 反之就查询到子集合
            List<IllSubEntity> children = this.getChildren(depId);
            illSubTitleAndIdVos = children.stream().map(item -> {
                IllSubTitleAndIdVo illSubTitleAndIdVo = new IllSubTitleAndIdVo();
                BeanUtils.copyProperties(item, illSubTitleAndIdVo);
                return illSubTitleAndIdVo;
            }).collect(Collectors.toList());
        }

        return illSubTitleAndIdVos;

    }

    /**
     * 获取医生分页数据
     */
    @Override
    public PageUtils queryDoctorPage(Map<String, Object> params) {

        LambdaQueryWrapper<DoctorInfoEntity> doctorInfoWrapper = new LambdaQueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            doctorInfoWrapper.and(obj -> {
                obj.eq(BaseEntity::getId, key).or().like(DoctorInfoEntity::getName, key);
            });
        }
        doctorInfoWrapper.orderByDesc(BaseEntity::getUpdateTime);

        IPage<DoctorInfoEntity> page = doctorInfoService.page(
                new Query<DoctorInfoEntity>().getPage(params),
                doctorInfoWrapper
        );

        List<DoctorInfoEntity> records = page.getRecords();
        records = records.stream().peek(item -> {
            IllSubEntity subEntity = this.getById(item.getDepId());
            SysUserEntity userEntity = sysUserService.getById(item.getUserId());
            item.getParam().put("depTitle", subEntity != null && StringUtils.isNotEmpty(subEntity.getTitle()) ? subEntity.getTitle() : "");
            item.getParam().put("sysUserName", userEntity != null && StringUtils.isNotEmpty(userEntity.getUsername()) ? userEntity.getUsername() : "");
        }).collect(Collectors.toList());

        page.setRecords(records);
        return new PageUtils(page);
    }

    @Override
    public List<IllSubTitleAndIdVo> getTwoList() {
        // 获取到当前医生的
        DoctorInfoEntity doctorInfo = DoctorInfoUtils.getDoctorInfo(doctorInfoService);
        Long depId = doctorInfo.getDepId();
        LambdaQueryWrapper<IllSubEntity> illSubEntityWrapper = new LambdaQueryWrapper<>();
        illSubEntityWrapper.eq(IllSubEntity::getParentId, depId);
        List<IllSubEntity> list = this.list(illSubEntityWrapper);
        IllSubEntity subEntity = this.getById(depId);
        list.add(subEntity);
        return list.stream().map(item -> {
            IllSubTitleAndIdVo illSubTitleAndIdVo = new IllSubTitleAndIdVo();
            BeanUtils.copyProperties(item, illSubTitleAndIdVo);
            return illSubTitleAndIdVo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<Long> getChildrenAndParent(Long parentId) {
        List<IllSubEntity> children = this.getChildren(parentId);
        List<Long> resultIds = children.stream().map(IllSubEntity::getId).collect(Collectors.toList());
        resultIds.add(parentId);
        return resultIds;
    }
}